package com.ctyon.watchmanager.ui.fragment;

import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.ctyon.common.util.DataUtil;
import com.ctyon.common.util.TSnackbarUtil;
import com.ctyon.netlibrary.net.revert.BaseResponseEntity;
import com.ctyon.netlibrary.use.BaseObserver;
import com.ctyon.watchmanager.BasicApp;
import com.ctyon.watchmanager.R;
import com.ctyon.watchmanager.bean.ProgramBean;
import com.ctyon.watchmanager.databinding.FragmentProgramBinding;
import com.ctyon.watchmanager.listener.ProgramItemClickListener;
import com.ctyon.watchmanager.model.net.service.NetService;
import com.ctyon.watchmanager.ui.BaseFragment;
import com.ctyon.watchmanager.ui.adapter.ProgramAdapter;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * CreateDate：19-6-25 on 上午9:14
 * Describe:
 * Coder: lee
 */
public class ProgramFragment extends BaseFragment {

    public static final String TAG = "ProgramFragment";

    private FragmentProgramBinding mBinding;
    private ProgramAdapter mAdapter;
    private String programStr;

    private List<ProgramBean> programList = new ArrayList<>();
    private String[] programName;
    private TypedArray programIcon;
    private List<String> programCmd = new ArrayList<>();
    List<ProgramBean> list = new ArrayList<>();

    public static ProgramFragment newInstance() {
        final ProgramFragment fragment = new ProgramFragment();
        final Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_program, container, false);

        mAdapter = new ProgramAdapter(itemClickListener);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        mBinding.programRecycle.setLayoutManager(layoutManager);
        mBinding.programRecycle.setAdapter(mAdapter);

        return mBinding.getRoot();

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (null == programName) {
            programName = BasicApp.getInstance().getApplicationContext().getResources().getStringArray(R.array.programName);
        }
        if (null == programIcon) {
            programIcon = BasicApp.getInstance().getApplicationContext().getResources().obtainTypedArray(R.array.programsIcon);
        }
        if (0 == programCmd.size()) {
            String[] strings = BasicApp.getInstance().getApplicationContext().getResources().getStringArray(R.array.programCmd);
            Collections.addAll(programCmd, strings);
        }
        programStr = BasicApp.getInstance().getWatch().getAppLock();
        programList.clear();
        if (!DataUtil.isEmptyAnd(programStr) && programStr.contains("&")) {
            String[] strings = programStr.split("&");
            for (String s : strings) {
                String[] p = s.split("-");
                String name = getName(p[0]);
                Drawable icon = getIcon(p[0]);
                if (DataUtil.isEmptyOr(name)) {
                    continue;
                }
                ProgramBean programBean = new ProgramBean(p[0], name, icon, Integer.valueOf(p[1]) == 1);
                programList.add(programBean);
            }

        }
        mAdapter.setData(programList);
    }

    private final ProgramItemClickListener<Integer> itemClickListener = (position, enable) -> {
        Logger.t(LTAG).i("position = " + position + "  enable = " + enable);
        list.clear();
        list.addAll(programList);
        list.get(position).setEnable(enable);
        final StringBuilder programsData = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            if (i > 0){
                programsData.append("&");
            }
            programsData.append(list.get(i).toString());
        }
        String data = programsData.toString();
        Logger.t(LTAG).d("data : " + data);
        if (programStr.equals(data)){
            return;
        }
        final String method = "program";
        if (NetService.getInstance().isDisable(method)) {
            TSnackbarUtil.TSBError(getActivity(), "请稍候...");
            return;
        }
        NetService.getInstance()
                .method(method)
                .program(BasicApp.getInstance().getManager().getManagerId(), BasicApp.getInstance().getWatch().getMeid(), data)
                .timeout(10, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponseEntity>() {
                    @Override
                    public void onSuccess(BaseResponseEntity responseEntity) {
                        Logger.d("onSuccess : " + responseEntity.toString());
                        TSnackbarUtil.TSBSuccess(getActivity(), "操作成功");
                        BasicApp.getInstance().getWatch().setAppLock(data);
                        programStr = data;
                        programList.get(position).setEnable(enable);
                    }

                    @Override
                    public String onOver() {
                        return method;
                    }
                });

    };

    private String getName(String cmd) {
        int index = programCmd.indexOf(cmd);
        if (-1 != index) {
            return programName[index];
        }
        return null;
    }

    private Drawable getIcon(String cmd) {
        int index = programCmd.indexOf(cmd);
        if (-1 != index) {
//            return programIcon.getResourceId(index, 0);
            return programIcon.getDrawable(index);
        }
        return null;
    }

}
